import 'dart:convert';

import 'package:dio/dio.dart';

import 'osc_notice_v2.dart';

class OscBaseEntity<T> {
	T result;
	int code = 0;
	String time;
	String message;
	OscNoticeV2 notice;
	bool success = false;

	factory OscBaseEntity(jsonStr, Function buildFun, {bool isBoolResult = false}){
		if(jsonStr != null) {
			if(jsonStr is Response) {
				var data = jsonStr.data;
				return data is String ? OscBaseEntity.fromJson(json.decode(data), buildFun, isBoolResult: isBoolResult) : OscBaseEntity.fromJson(data, buildFun, isBoolResult: isBoolResult);
			} else {
				return jsonStr is String ? OscBaseEntity.fromJson(json.decode(jsonStr), buildFun, isBoolResult: isBoolResult) : OscBaseEntity.fromJson(jsonStr, buildFun, isBoolResult: isBoolResult);
			}
		} else {
			return OscBaseEntity.fromParams(code: 9999, message: "request no response", success: false);
		}
	}

	OscBaseEntity.fromParams({this.code, this.message, this.result, this.success, this.notice, this.time});
	OscBaseEntity.fromJson(jsonRes, Function buildFun, {bool isBoolResult = false}) {
		code = jsonRes['code'];
		message = jsonRes['message'];
		time = jsonRes['time'];
		notice = jsonRes['notice'] != null ? new OscNoticeV2.fromJson(jsonRes['notice']) : null;

		if(code == 1){
			success = true;
		}

		if(jsonRes['result'] != null) {
			if (isBoolResult) {
				result = jsonRes['result'];
			} else {
				if (buildFun != null) {
					result = buildFun(jsonRes['result']);
				}
			}
		}
	}

	Map<String, dynamic> toJson() {
		final Map<String, dynamic> data = new Map<String, dynamic>();
		data['code'] = this.code;
		data['message'] = this.message;
		data['time'] = this.time;
		data['result'] = this.result;
		if (this.notice != null) {
			data['notice'] = this.notice.toJson();
		}
		return data;
	}
}

